package com.drinks.yiniang.ui.widget.edittext;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatEditText;
import android.text.InputFilter;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.drinks.yiniang.R;
import com.hansen.library.utils.ScreenSizeUtils;

/**
 * 验证码输入框,重写EditText的绘制方法实现。
 * @author han
 * @date 2019/9/5
 */
public class CodeEditText extends AppCompatEditText {

    private Context mContext;

    // 输入的最大长度
    private int mMaxLength = 6;
    // 边框宽度
    private int mStrokeWidth;
    // 边框高度
    private int mStrokeHeight;
    // 边框之间的距离
    private int mStrokePadding;
    //颜色
    private int mTextColor;
    //文字大小
    private int mTextSize;

    //当前激活下标横线
    private Paint mActiveLinePaint;
    private int mLineStrokeWidth = 6;
    private int mLineWidth;

    // 方框的背景
    private Drawable mStrokeDrawable;

    private final Rect mRect = new Rect();

    private OnCodeTextFinishListener onCodeTextFinishListener;

    public CodeEditText(Context context) {
        this(context, null);
    }

    public CodeEditText(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CodeEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mContext = context;

        init();
    }

    private void init() {
        mStrokeWidth = ScreenSizeUtils.dp2px(mContext, 44);
        mStrokeHeight = mStrokeWidth;

        mStrokePadding = ScreenSizeUtils.dp2px(mContext, 10);

        mStrokeDrawable = ContextCompat.getDrawable(mContext, R.drawable.shape_bkg_verification_code);

        mTextColor = ContextCompat.getColor(mContext, R.color.color_0c0c0c);
        mTextSize = ScreenSizeUtils.sp2px(20);

        mLineWidth = ScreenSizeUtils.dp2px(mContext, 10);

        setMaxLength(mMaxLength);
        setLongClickable(false);
        setTextColor(Color.TRANSPARENT);
        setTextSize(0);
        // 去掉背景颜色
        setBackgroundColor(Color.TRANSPARENT);
        // 不显示光标
        setCursorVisible(false);
        setFocusable(true);
        setFocusableInTouchMode(true);

        mActiveLinePaint = new Paint();

        mActiveLinePaint.setStyle(Paint.Style.STROKE);
        mActiveLinePaint.setColor(ContextCompat.getColor(mContext, R.color.color_ec6259));
        mActiveLinePaint.setStrokeWidth(mLineStrokeWidth);
        mActiveLinePaint.setAntiAlias(true);

        //每次点击设置光标移动到最后
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(getEditableText().length() > 0) {
                    setSelection(getEditableText().length());
                }
            }
        });
    }

    @Override
    public boolean onTextContextMenuItem(int id) {//屏蔽复制粘贴
        return false;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        // 判断高度是否小于推荐高度
        if (height < mStrokeHeight) {
            height = mStrokeHeight;
        }

        // 判断高度是否小于推荐宽度
        int recommendWidth = mStrokeWidth * mMaxLength + mStrokePadding * (mMaxLength - 1);

        if (width < recommendWidth) {
            width = recommendWidth;
        }

        widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, widthMode);
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, heightMode);

        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        getPaint().setTextSize(1);
        super.onDraw(canvas);
        // 重绘背景颜色
        drawStrokeBackground(canvas);
        // 重绘文本
        drawText(canvas);
    }


    /**
     * 重绘背景
     */
    private void drawStrokeBackground(Canvas canvas) {
        // 绘制方框背景颜色
        mRect.left = 0;
        mRect.top = 0;
        mRect.right = mStrokeWidth;
        mRect.bottom = mStrokeHeight;

        int count = canvas.getSaveCount();

        canvas.save();

        for (int i = 0; i < mMaxLength; i++) {
            mStrokeDrawable.setBounds(mRect);
            mStrokeDrawable.setState(new int[]{android.R.attr.state_enabled});
            mStrokeDrawable.draw(canvas);
            float dx = mRect.right + mStrokePadding;
            // 移动画布
            canvas.save();
            canvas.translate(dx, 0);
        }

        canvas.restoreToCount(count);
        canvas.translate(0, 0);

        // 绘制激活状态的边框
        // 当前激活的索引
        int activatedIndex = Math.max(0, getEditableText().length());

        mRect.left = mStrokeWidth * activatedIndex + mStrokePadding * activatedIndex;
        mRect.right = mRect.left + mStrokeWidth;
//        mStrokeDrawable.setState(new int[]{android.R.attr.state_focused});
//        mStrokeDrawable.setBounds(mRect);
//        mStrokeDrawable.draw(canvas);

        if(activatedIndex < mMaxLength) {
            int startX = mRect.left + mStrokeWidth / 2 - mLineWidth / 2;
            int startY = mRect.top + mStrokeHeight / 2;

            canvas.drawLine(startX, startY, startX + mLineWidth, startY, mActiveLinePaint);
        }
    }

    /**
     * 重绘文本
     */
    private void drawText(Canvas canvas) {
        int count = canvas.getSaveCount();
        canvas.translate(0, 0);
        int length = getEditableText().length();
        for (int i = 0; i < length; i++) {
            String text = String.valueOf(getEditableText().charAt(i));
            TextPaint textPaint = getPaint();
            textPaint.setColor(mTextColor);
            textPaint.setTextSize(mTextSize);
            // 获取文本大小
            textPaint.getTextBounds(text, 0, 1, mRect);
            // 计算(x,y) 坐标
            int x = mStrokeWidth / 2 + (mStrokeWidth + mStrokePadding) * i - (mRect.centerX());
            int y = canvas.getHeight() / 2 + mRect.height() / 2;
            canvas.drawText(text, x, y, textPaint);
        }
        canvas.restoreToCount(count);
    }

    @Override
    protected void onTextChanged(CharSequence text, int start,
                                 int lengthBefore, int lengthAfter) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter);

        // 当前文本长度
        int textLength = getEditableText().length();

        if (textLength == mMaxLength) {
            hideSoftInput();
            if (onCodeTextFinishListener != null) {
                onCodeTextFinishListener.onCodeTextFinish(getEditableText().toString(), mMaxLength);
            }
        }
    }


    public void hideSoftInput() {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null)
            imm.hideSoftInputFromWindow(getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 设置最大长度
     */
    private void setMaxLength(int maxLength) {
        if (maxLength >= 0) {
            setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
        } else {
            setFilters(new InputFilter[0]);
        }
    }

    public void setOnCodeTextFinishListener(OnCodeTextFinishListener onCodeTextFinishListener) {
        this.onCodeTextFinishListener = onCodeTextFinishListener;
    }

    public interface OnCodeTextFinishListener {

        void onCodeTextFinish(CharSequence text, int length);
    }
}
